package com.cky.forum.services.impl;

import com.cky.forum.common.AppResult;
import com.cky.forum.common.ResultCode;
import com.cky.forum.dao.UserMapper;
import com.cky.forum.exception.ApplicationException;
import com.cky.forum.model.User;
import com.cky.forum.services.IUserService;
import com.cky.forum.util.MD5Util;
import com.cky.forum.util.StringUtil;
import com.cky.forum.util.UUIDUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Date;

@Slf4j
@Service
public class UserServiceImpl implements IUserService {
    @Resource
    private UserMapper userMapper;
    @Override
    public void createNormalUser(User user) {
        //非空校验
        if(user == null || StringUtil.isEmpty(user.getUsername())
        || StringUtil.isEmpty(user.getNickname())
        ||StringUtil.isEmpty(user.getPassword())
        ||StringUtil.isEmpty(user.getSalt())){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常,统一抛applicationException
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //按用户名查询用户信息
        User existsUser = userMapper.selectByUserName(user.getUsername());
        //判断用户是否存在
        if(existsUser != null){
            log.warn(ResultCode.FAILED_USER_EXISTS.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_EXISTS));
        }
        //新增用户流程，设置默认值
        user.setGender((byte)2);
        user.setArticleCount(0);
        user.setIsAdmin((byte)0);
        user.setState((byte)0);
        user.setDeleteState((byte)0);
        //当前日期
        Date date = new Date();
        user.setCreateTime(date);
        user.setUpdateTime(date);
        int row = userMapper.insertSelective(user);
        if(row != 1){
            log.info(ResultCode.FAILED_CREATE.toString());
            //抛异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));
        }
        //打印日志
        log.info("新增用户成功. username = " + user.getUsername());
    }

    @Override
    public User selectByUserName(String username) {
        if(StringUtil.isEmpty(username)){
            //抛异常
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //返回查询的结果
        return userMapper.selectByUserName(username);
    }

    @Override
    public User login(String username, String password) {
        //非空校验
        //按用户名查询用户信息
        //查询结果做非空校验
        //对密码做校验
        if(StringUtil.isEmpty(username) || StringUtil.isEmpty(password)){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        User user = selectByUserName(username);
        if(user == null){
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        String encryptPassword = MD5Util.md5Salt(password,user.getSalt());
        if(!encryptPassword.equalsIgnoreCase(user.getPassword())){
            log.warn(ResultCode.FAILED_LOGIN.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_LOGIN));
        }
        log.info("登录成功" + username);
        return user;
    }

    @Override
    public User selectById(Long id) {
    //非空校验
        if(id == null){
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_LOGIN));
        }
        User user = userMapper.selectByPrimaryKey(id);
        return user;
    }

    @Override
    public void addOneArticleCountById(Long id) {
        if(id == null || id <= 0){
            log.warn(ResultCode.FAILED_BOARD_ARTICLE_COUNT.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_BOARD_ARTICLE_COUNT));
        }
        //查询对应板块
        User user = userMapper.selectByPrimaryKey(id);
        if(user == null){
            log.warn(ResultCode.ERROR_IS_NULL.toString() + ",user id = " +id);
            //抛异常
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_IS_NULL));
        }
        User updateUser = new User();
        updateUser.setId(user.getId());
        updateUser.setArticleCount(user.getArticleCount()+1);
        //调用Dao，执行更新
        int row = userMapper.updateByPrimaryKeySelective(updateUser);

        if(row != 1){
            log.warn(ResultCode.FAILED.toString() + "，受影响的行数不等于1");
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
    }

    @Override
    public void subOneArticleCountById(Long id) {
        if(id == null || id <= 0){
            log.warn(ResultCode.FAILED_BOARD_ARTICLE_COUNT.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_BOARD_ARTICLE_COUNT));
        }
        //查询对应板块
        User user = userMapper.selectByPrimaryKey(id);
        if(user == null){
            log.warn(ResultCode.ERROR_IS_NULL.toString() + ",user id = " +id);
            //抛异常
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_IS_NULL));
        }
        User updateUser = new User();
        updateUser.setId(user.getId());
        updateUser.setArticleCount(user.getArticleCount()-1);
        //调用Dao，执行更新
        if(updateUser.getArticleCount() < 0){
            updateUser.setArticleCount(0);
        }
        int row = userMapper.updateByPrimaryKeySelective(updateUser);

        if(row != 1){
            log.warn(ResultCode.FAILED.toString() + "，受影响的行数不等于1");
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
    }

    @Override
    public void modifyInfo(User user) {
        if(user == null || user.getId() == null){
            log.warn(ResultCode.ERROR_IS_NULL.toString() + ",user id = " +user.getId());
            //抛异常
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_IS_NULL));
        }
        User existsUser = userMapper.selectByPrimaryKey(user.getId());
        if(existsUser == null){
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        boolean checkAttr = false;
        User updateUser = new User();
        System.out.println(user.getId());
        updateUser.setId(user.getId());
        System.out.println(updateUser.getId());
        if(!StringUtil.isEmpty(user.getUsername())
        || !existsUser.getUsername().equals(user.getUsername())){
            User checkUser = userMapper.selectByUserName(user.getUsername());
            if(checkUser != null){
                log.warn(ResultCode.FAILED_USER_EXISTS.toString());
                throw new ApplicationException(AppResult.failed(ResultCode.FAILED_NOT_EXISTS));
            }
            updateUser.setUsername(user.getUsername());
            checkAttr = true;
        }
        if(!StringUtil.isEmpty(user.getNickname())
        && !existsUser.getNickname().equals(user.getNickname())){
            updateUser.setNickname(user.getNickname());
            checkAttr = true;
        }
        if(user.getGender() != null
        && existsUser.getGender() != user.getGender()){
            updateUser.setGender(user.getGender());
            if(updateUser.getGender() > 2 || updateUser.getGender() < 0){
                updateUser.setGender((byte)2);
            }
            checkAttr = true;
        }
        if(!StringUtil.isEmpty(user.getEmail())
        && !user.getEmail().equals(existsUser.getEmail())){
            updateUser.setEmail(user.getEmail());
           checkAttr = true;
        }
        if(!StringUtil.isEmpty(user.getPhoneNum())
        && !user.getPhoneNum().equals(existsUser.getPhoneNum())){
            updateUser.setPhoneNum(user.getPhoneNum());
            checkAttr = true;
        }
       if(!StringUtil.isEmpty(user.getRemark())
        && !user.getRemark().equals(existsUser.getRemark())){
            updateUser.setRemark(user.getRemark());
            checkAttr = true;
        }
//        updateUser.setEmail(existsUser.getEmail());
//        updateUser.setRemark(user.getRemark());
        if(checkAttr == false){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        int row = userMapper.updateByPrimaryKeySelective(updateUser);
        if(row != 1){
            log.warn(ResultCode.FAILED.toString() + "受影响的行数不等于1");
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
    }

    @Override
    public void modifyPassword(Long id, String newPassword, String oldPassword) {
        if(id == null || id<=0 || StringUtil.isEmpty(newPassword) || StringUtil.isEmpty(oldPassword)){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw  new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        User user = userMapper.selectByPrimaryKey(id);
        if(user == null || user.getDeleteState() == 1){
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        String oldEncryptPassword = MD5Util.md5Salt(oldPassword,user.getSalt());
        if(oldEncryptPassword.equalsIgnoreCase(user.getPassword())){
            log.warn(ResultCode.FAILED.toString());
            throw  new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
        String salt = UUIDUtil.UUID_32();
        String encryptPassword = MD5Util.md5Salt(newPassword,salt);
        User updateUser = new User();
        updateUser.setId(user.getId());
        updateUser.setSalt(salt);
        updateUser.setPassword(encryptPassword);
        Date date = new Date();
        updateUser.setUpdateTime(date);
        int row = userMapper.updateByPrimaryKeySelective(updateUser);
        if(row != 1){
            log.warn(ResultCode.FAILED.toString() + ",受影响的行数不等于1.");
            throw  new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
    }
}
